package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //  后期需要进行md5加密，然后再进行比对 已完成
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 修改密码业务逻辑
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //获取请求参数
        //Long empId = passwordEditDTO.getEmpId();
        Long empId = BaseContext.getCurrentId();
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
        //参数校验
        if(empId == null || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

        //根据员工id查询员工信息
        Employee employee = employeeMapper.selectById(empId);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 存在账号，则验证旧密码是否正确
        String encryptedOldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());

        //加密后的密码与数据库密码是否一致
        if (!encryptedOldPassword.equals(employee.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (oldPassword.equals(newPassword)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

        //对新密码进行加密
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        //更新员工密码

        employee.setPassword(encryptedNewPassword);
        employeeMapper.updateEmp(employee); //更新员工密码,将更新后的员工密码保存到数据库中
    }

    /**
     * 新增员工业务逻辑
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //需要手动设置employee中的其他属性

        Employee employee = new Employee();

        //对象 属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号的状态，默认正常状态：1 锁定：0
//        employee.setStatus(1);
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码，默认123456
//        employee.setPassword("123456");
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes())); //md5加密

        //设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //设置当前记录创建人id和修改人id
        //后期需改为当前登录用户的id
//        employee.setCreateUser(10L);
//        employee.setUpdateUser(10L);
//        //
        employeeMapper.save(employee);


    }

    /**
     * 员工分页查询业务逻辑
     * @param employeePageQueryDTO
     * @return
     */

    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        //使用分页插件
        //1.设置分页数
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //执行查询
//        List<Employee> list = employeeMapper.page(employeePageQueryDTO);
//        Page<Employee> p = (Page<Employee>) list;
        Page<Employee> pages = employeeMapper.page(employeePageQueryDTO);
        //封装结果
        return new PageResult(pages.getTotal(), pages.getResult());
    }

    /**
     * 启动禁用业务逻辑
     * @param status
     * @param id
     */

    @Override
    public void startStop(Integer status, Long id) {

        employeeMapper.startStop(status, id);

    }

    /**
     * 根据id查询员工业务逻辑
     * @return
     */
    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectById(id);
    }

    /**
     * 编辑员工信息逻辑
     * @param employeeDTO
     * @return
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();
        //对象 属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //修改更新时间
//        employee.setUpdateTime(LocalDateTime.now());

//        employee.setCreateUser(10L);
//        employee.setUpdateUser(10L);
        employeeMapper.updateEmp(employee);
    }
}
